const cache = require('lib/cache'),
    security = require('lib/security'),
    config = require('config'),
    utils = require('lib/utils');

const { cookieKey } = config.security;

/**
 * Created by cr. on 2017/8/29.
 * 用于对请求报文预处理，并为后续提供基础方法
 */
module.exports = function*(next) {
    //自定义报头或参数解析
    let { token } = this.request.header;
    let cookie = this.cookies.get(cookieKey)
    if (!cookie) cookie = token; //用于更新redis信息

    this.getSession = function*(token = cookie) {
        try {
            if (token) {
                let [secret, adminId] = security.decipher(token).split(":");
                let session = yield cache.get(`${adminId}`);
                return session;
            }
            return null;
        } catch (error) {
            return null;
        }
    };

    this.setSession = function*(seems, token = cookie) {
        let [secret, adminId] = security.decipher(token).split(":");
        return yield cache.set(`${adminId}`, seems);
    };


    this.sign = function(adminId) {
        cookie = security.cipher(`${utils.randomCode(15)}:${adminId}`);
        this.cookies.set(cookieKey, cookie);
        return cookie;
    };

    //其他方法
    this.success = (data) => ({
        code: 200,
        error: null,
        result: data
    });

    this.fail = (msg, code) => {
        code = code || 500;
        this.status = code;
        return {
            code,
            error: msg || "system error",
            result: null
        }
    };

    yield next;
}